<?php
namespace Home\Controller;

use Think\Controller;

/**
 * 其他管理
 * @author DONGGUIYU
 *
 */
class OtherController extends Controller
{
    /**
     * 城市管理
     */
    public function cityList(){
        $cityModel = D('City');
        // 分页
        $page = setPage($cityModel);
        // 进行分页数据查询
        $orderby['id']='asc';
        $rlt = $cityModel->order($orderby)->limit($page->firstRow.','.$page->listRows)->select();
        $show = $page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        
        //$rlt = $cityModel->select();
        if(isset($rlt)){
            $cities = array();
            foreach ($rlt as $city){
                $adjoinIdList = split(',', $city['adjoin_city_id']);
                $adjoinCityNameStr = "";
                foreach ($adjoinIdList as $adjoinId){
                    $where['id'] = $adjoinId;
                    $adjoinCityName = $cityModel->where($where)->getField('name');
                    if(empty($adjoinCityNameStr)){
                        $adjoinCityNameStr.=$adjoinCityName;
                    } else {
                        $adjoinCityNameStr.= ",".$adjoinCityName;
                    }
                }
                $city['adjoinCities'] = $adjoinCityNameStr;
                $cities[] = $city;
            }
            $this->assign('cities', $cities);
        }
        $this->display('citylist');
    }
    
    /**
     * 保存城市
     */
    public function saveCity(){
        // 城市ID
        $id =  I('post.cityId', "", 'htmlspecialchars');
        // 城市名称
        $cityName = I('post.cityName', "", 'htmlspecialchars');
        if (isset($cityName)
                && strlen(trim($cityName)) > 0) {
           $cityNameArray = split(',', $cityName);
           if (isset($cityNameArray)
               && is_array($cityNameArray)
               && count($cityNameArray) > 0) {
               foreach($cityNameArray as $name) {
                   // 判断要添加的城市是否已经存在
                   $rlt = $this->getCitiesProc(null, $name);
                   // 城市model
                   $cityModel = D('City');
                   $cityModel->startTrans();
                   if (count($rlt) == 0) {
                       // 添加城市
                       if(empty($id)){
                           $data['name'] = $name;
                           $rlt = $cityModel->data($data)->add();
                       } else {
                           // 修改城市
                           $where['id'] = $id;
                           $rlt = $cityModel->where($where)->save($data);
                       }
                   }
//                    } else {
//                        $this->error("[".$name."]已经存在！");
//                    }
               }
           }       
        }
        if($rlt != 0 && $rlt == false){
            $cityModel->rollback();
            $this->error("保存失败！");
            exit;
        } else {
            $cityModel->commit();
            $this->success("保存成功！", "cityList");
            exit;
        }
    }
    
    /**
     * 获取城市
     */
    private function getCitiesProc($cityId, $cityName) {
        // 判断城市ID是否为有效值
        if (isset($cityId)
            && is_numeric(trim($cityId))
            && intval(trim($cityId)) > 0) {
            // 设定检索条件
            $where['id'] = trim($cityId);
        }
        // 判断城市名称是否为有效值
        if (isset($cityName)
            && strlen(trim($cityName)) > 0) {
            // 设定检索条件
            $where['name'] = trim($cityName);
        }
        $cityModel = D('City');
        if (isset($where)) {
            $rlt = $cityModel->where($where)->select();
        } else {
            $rlt = $cityModel->select();
        }
        if (isset($rlt)) {
            return $rlt;
        } else {
            return array();
        }
    }
    
    /**
     * 删除城市
     */
    public function deleteCity(){
        $idList = I('post.idList', "", 'htmlspecialchars');
        // 城市model
        $cityModel = D('City');
        $cityModel->startTrans();
        if(!empty($idList)){
            $idArray = split(',', $idList);
            // 开启事务
            $cityModel->startTrans();
            foreach ($idArray as $id){
                $where['id'] = $id;
                $rlt = $cityModel->where($where)->delete();
                if($rlt == false){
                    // 删除失败时回滚事务
                    $cityModel->rollback();
                    $this->error("删除失败！");
                    exit;
                }
            }
            // 提交事务
            $cityModel->commit();
            $this->success("删除成功！", 'cityList');
        }
    }
    
    /**
     * 获取其他城市
     * @return 其他城市列表(json形式)
     */
    public function getOtherCity(){
        // 城市ID
        $id =  I('post.cityId', "", 'htmlspecialchars');
        // 判断城市ID是否为有效值
        if (isset($id)
            && is_numeric(trim($id))
            && intval(trim($id)) > 0) {
                // 设定检索条件
                $where['id'] = array('neq',trim($id));
            }
            $cityModel = D('City');
            if (isset($where)) {
                $rlt = $cityModel->where($where)->select();
            } else {
                $rlt = $cityModel->select();
            }
            if (isset($rlt)) {
                unset($where);
                $where['id'] = $id;
                $adjoinIdList = $cityModel->where($where)->getField('adjoin_city_id');
                if(isset($adjoinIdList)){
                    $adjoinCities = split(',', $adjoinIdList);
                    foreach ($rlt as $city){
                        if(in_array($city['id'], $adjoinCities) == false){
                            $item[] = $city;
                        }
                    }
                }
                echo  json_encode($item);
            } else {
                echo  json_encode(array());
            }
    }
    
    // ======== 密保问题   开始 ==========
    /**
     * 密保问题管理
     */
    public function securityQuestion(){
        $securityQuestionModel = D('SecurityQuestion');
        $rlt = $securityQuestionModel->select();
        $this->assign("security_questions",$rlt);
        $this->display("securityquestion");
    }
    
    /**
     * 添加密保问题
     */
    public function addSecurityQuestion(){
        $this->assign('title','添加密保问题');
        $this->display('editquestion');
    }
    
    /**
     * 编辑密保问题
     */
    public function editSecurityQuestion(){
        $this->assign('title','修改密保问题');
        $securityQuestionModel = D('SecurityQuestion');
        $id = I('get.id', '', 'htmlspecialchars');
        $where['id'] = $id;
        $question = $securityQuestionModel->where($where)->select();
        $this->assign('question', $question[0]);
        $this->display('editquestion');
    }
    
    /**
     * 检查要保存的密保问题是否已经存在
     */
    public function hasExisted(){
        $id = I('post.id', '', 'htmlspecialchars');
        // 密保问题
        $question = I('post.question', '', 'htmlspecialchars');
    
        if(!empty($question)){
            $params['question'] = $question;
            $message = "您输入的问题";
        }
        if(!empty($id)){
            $where['id'] = $id;
            $securityQuestionModel = D('SecurityQuestion');
            $rlt = $securityQuestionModel->where($where)->select();
            if($rlt[0]['question'] == $question){
               echo json_encode(array("status"=>500,"message"=>"不存在"));
               exit;
            } else {
                if($this->checkHasExisted($params) == true){
                    echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
                } else {
                    if(empty($params)){
                        echo json_encode(array("status"=>500,"message"=>"不存在"));
                    } else {
                        if($this->checkHasExisted($params) == true){
                            echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
                        } else {
                            echo json_encode(array("status"=>500,"message"=>"不存在"));
                        }
                    }
                }
            }
        } else {
            if($this->checkHasExisted($params) == true){
                echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
            } else {
                echo json_encode(array("status"=>500,"message"=>"不存在"));
            }
        }
    }
    
    /**
     * 检查密保问题是否已经存在
     * @param $params key:DB中各个字段名。如：`question`.value:DB中各个字段所对应的值。如"你的生日是什么时候?"
     * @return boolean
     */
    private function checkHasExisted($params = array()){
        $securityQuestionModel = D('SecurityQuestion');
        foreach ($params as $key=>$value){
            $where[$key] = $value;
        }
        $rlt = $securityQuestionModel->where($where)->getField("id");
        if($rlt > 0){
            return true; // 已存在
        } else {
            return false;  // 不存在
        }
    }
    
    /**
     * 保存密保问题
     */
    public function saveSecurityQuestion(){
        $securityQuestionModel = D('SecurityQuestion');
        $id = I('post.id', '', 'htmlspecialchars');
         
        // 问题
        $question = I('post.question','','htmlspecialchars');
         
        $data['question'] = $question;
         
        if(intval($id) > 0){
            $where['id'] = $id;
            $rlt = $securityQuestionModel->where($where)->save($data);
            if($rlt != 0 && $rlt == false){
                $this->error('密保问题修改失败！');
            } else {
                $this->success('密保问题修改成功', 'securityQuestion');
            }
        } else {
            $rlt = $securityQuestionModel->data($data)->add();
            if($rlt != 0 && $rlt == false){
                $this->error('添加密保问题失败！');
            } else {
                $this->success('添加密保问题成功', 'securityQuestion');
            }
        }
         
    }
    
    /**
     * 删除密保问题
     */
    public function deleteSecurityQuestion(){
        $idList = I('post.idList', "", 'htmlspecialchars');
        // 密保问题model
        $securityQuestionModel = D('SecurityQuestion');
        if(!empty($idList)){
            $idArray = split(',', $idList);
            
            foreach ($idArray as $id){
                unset($where);
                $where['question_1_id'] = $id;
                $where['question_2_id'] = $id;
                $where['question_3_id'] = $id;
                $where["_logic"] = "OR";
                $securityAnswerModel = D('SecurityAnswer');
                $rlt = $securityAnswerModel->where($where)->select();
                if(!empty($rlt) && count($rlt) > 0){
                    $this->error("该密保问题正在使用中，不能删除！");
                    exit;
                } else {
                    unset($where);
                    $where['id']= $id;
                    // 开启事务
                    $securityQuestionModel->startTrans();
                    $rlt = $securityQuestionModel->where($where)->delete();
                    if($rlt == false){
                        // 删除失败时回滚事务
                        $securityQuestionModel->rollback();
                        $this->error("删除失败！");
                        exit;
                    }
                }
            }
            // 提交事务
            $securityQuestionModel->commit();
            $this->success("删除成功！", 'securityQuestion');
        }
    }
    // ======== 密保问题  结束 ==========
    
    // ======== 协议   开始 ==========
    /**
     * 协议管理
     */
    public function protocol(){
        $protocolModel = D('Protocol');
        $rlt = $protocolModel->select();
        $protocolList = array();
        foreach ($rlt as $protocol){
            $item = $protocol;
            if(mb_strlen($item['about'],"utf8") >= 150){
                $item['about'] = mb_substr($item['about'],0,147,"utf8")."...";
            }
            $protocolList[] = $item;
        }
        $this->assign("protocol_list",$protocolList);
        $this->display("protocol");
    }
    
    /**
     * 添加协议
     */
    public function addProtocol(){
        $this->assign('title','添加协议');
        $this->display('editprotocol');
    }
    
    /**
     * 编辑协议
     */
    public function editProtocol(){
        $this->assign('title','修改协议');
        $protocolModel = D('Protocol');
        $id = I('get.id', '', 'htmlspecialchars');
        $where['id'] = $id;
        $protocol = $protocolModel->where($where)->select();
        $protocol[0]['protocol'] = html_entity_decode($protocol[0]['protocol']);
        $this->assign('protocol', $protocol[0]);
        $this->display('editprotocol');
    }
    
    /**
     * 检查要保存的协议是否已经存在
     */
    public function hasProtocolExisted(){
        $id = I('post.id', '', 'htmlspecialchars');
        // 协议标题
        $protocolTitle = I('post.protocol_title', '', 'htmlspecialchars');
    
        if(!empty($protocolTitle)){
            $params['protocol_title'] = $protocolTitle;
            $message = "您要创建的协议";
        }
        if(!empty($id)){
            $where['id'] = $id;
            $protocolModel = D('Protocol');
            $rlt = $protocolModel->where($where)->select();
            if($rlt[0]['protocol_title'] == $protocolTitle){
                echo json_encode(array("status"=>500,"message"=>"不存在"));
                exit;
            } else {
                if($this->checkHasProtocolExisted($params) == true){
                    echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
                } else {
                    if(empty($params)){
                        echo json_encode(array("status"=>500,"message"=>"不存在"));
                    } else {
                        if($this->checkHasProtocolExisted($params) == true){
                            echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
                        } else {
                            echo json_encode(array("status"=>500,"message"=>"不存在"));
                        }
                    }
                }
            }
        } else {
            if($this->checkHasProtocolExisted($params) == true){
                echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
            } else {
                echo json_encode(array("status"=>500,"message"=>"不存在"));
            }
        }
    }
    
    /**
     * 检查协议是否已经存在
     * @param $params key:DB中各个字段名。如：`protocol_title`.value:DB中各个字段所对应的值。如"义达协议"
     * @return boolean
     */
    private function checkHasProtocolExisted($params = array()){
        $protocolModel = D('Protocol');
        foreach ($params as $key=>$value){
            $where[$key] = $value;
        }
        $rlt = $protocolModel->where($where)->getField("id");
        if($rlt > 0){
            return true; // 已存在
        } else {
            return false;  // 不存在
        }
    }
    
    /**
     * 保存协议
     */
    public function saveProtocol(){
        $protocolModel = D('Protocol');
        $id = I('post.protocol_id', '', 'htmlspecialchars');
         
        // 协议标题
        $protocolTitle = I('post.protocol_title', '', 'htmlspecialchars');
        // 协议简介
        $protocolAbout= I('post.protocol_about', '', 'htmlspecialchars');
        // 协议内容
        $protocol = I('post.protocol', '', 'htmlspecialchars');
         
        $data['protocol_title'] = $protocolTitle;
        $data['about'] = $protocolAbout;
        $data['protocol'] = $protocol;
         
        if(intval($id) > 0){
            $where['id'] = $id;
            $rlt = $protocolModel->where($where)->save($data);
            if($rlt != 0 && $rlt == false){
                $this->error('修改协议失败！');
            } else {
                $this->success('修改协议成功', 'protocol');
            }
        } else {
            $rlt = $protocolModel->data($data)->add();
            if($rlt != 0 && $rlt == false){
                $this->error('创建协议失败！');
            } else {
                $this->success('创建协议成功', 'protocol');
            }
        }
         
    }
    
    /**
     * 删除密保问题
     */
    public function deleteProtocol(){
        $idList = I('post.idList', "", 'htmlspecialchars');
        // 协议model
        $protocolModel = D('Protocol');
        if(!empty($idList)){
            $idArray = split(',', $idList);
    
            foreach ($idArray as $id){
                unset($where);
                $where['id']= $id;
                // 开启事务
                $protocolModel->startTrans();
                $rlt = $protocolModel->where($where)->delete();
                if($rlt == false){
                    // 删除失败时回滚事务
                    $protocolModel->rollback();
                    $this->error("删除失败！");
                    exit;
                }
            }
            // 提交事务
            $protocolModel->commit();
            $this->success("删除成功！", 'protocol');
        }
    }
    // ======== 协议  结束 ==========
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    // ====== 周边城市  开始 ======
    /**
     * 获取周边城市
     * @return 其他城市列表(json形式)
     */
    public function getAdjoinCity(){
        // 城市ID
        $id =  I('post.cityId', "", 'htmlspecialchars');
        // 判断城市ID是否为有效值
        if (isset($id)
            && is_numeric(trim($id))
            && intval(trim($id)) > 0) {
                // 设定检索条件
                $where['id'] = trim($id);
            }
            $cityModel = D('City');
            if (isset($where)) {
                $rlt = $cityModel->where($where)->select();
            } else {
                $rlt = $cityModel->select();
            }
            if(isset($rlt)){
                $cities = array();
                foreach ($rlt as $city){
                    $adjoinIdList = split(',', $city['adjoin_city_id']);
                    $adjoinCityNameStr = "";
                    foreach ($adjoinIdList as $adjoinId){
                        $where['id'] = $adjoinId;
                        $adjoinCityName = $cityModel->where($where)->getField('name');
                        $item['id'] = $adjoinId;
                        $item['name'] = $adjoinCityName;
                        $cities[] = $item;
                    }
                }
                echo  json_encode($cities);
            } else {
                echo  json_encode(array());
            }
    }
    
    /**
     * 保存周边城市
     */
    public function saveAdjoinCities(){
        // 要添加的周边城市ID
        $idList = I('post.idList', "", 'htmlspecialchars');
        // 当前城市ID
        $id = I('post.cityId', "", 'htmlspecialchars');
        // 城市model
        $cityModel = D('City');
        $cityModel->startTrans();
        if(!empty($idList)){
            $where['id'] = $id;
            $adjoinIdList = $cityModel->where($where)->getField('adjoin_city_id');
            if(!empty($adjoinIdList)){
                $data['adjoin_city_id'] = $adjoinIdList.",".$idList;
            } else {
                $data['adjoin_city_id'] = $idList;
            }
            // 开启事务
            $cityModel->startTrans();
            $rs = $cityModel->where($where)->save($data);
            if($rs == false){
                // 删除失败时回滚事务
                $cityModel->rollback();
                $this->error("添加失败！");
                exit;
            }
            // 提交事务
            $cityModel->commit();
            $this->success("添加成功！", 'cityList');
        } else {
            $this->error("没有可保存的数据！");
        }
    }
    
    /**
     * 删除周边城市
     */
    public function removeAdjoinCities(){
        // 要添加的周边城市ID
        $idList = I('post.idList', "", 'htmlspecialchars');
        // 当前城市ID
        $id = I('post.cityId', "", 'htmlspecialchars');
        // 城市model
        $cityModel = D('City');
        $cityModel->startTrans();
        if(!empty($idList)){
            $where['id'] = $id;
            $adjoinIdList = $cityModel->where($where)->getField('adjoin_city_id');
            if(!empty($adjoinIdList)){
                $newAdjoinCities = "";
                $adjoinCities = split(',', $adjoinIdList);
                $removeCities = split(',', $idList);
                foreach ($removeCities as $removeCity){
                    $index = array_keys($adjoinCities, $removeCity);
                    array_splice($adjoinCities, $index[0],1);
                }
                foreach ($adjoinCities as $city){
                    if($newAdjoinCities == ""){
                        $newAdjoinCities = $city;
                    } else {
                        $newAdjoinCities.= ",".$city;
                    }
                }
                $data['adjoin_city_id'] =$newAdjoinCities;
                // 开启事务
                $cityModel->startTrans();
                $rs = $cityModel->where($where)->save($data);
                if($rs == false){
                    // 删除失败时回滚事务
                    $cityModel->rollback();
                    $this->error("删除失败！");
                    exit;
                }
                // 提交事务
                $cityModel->commit();
                $this->success("删除成功！", 'cityList');
            }
            else {
                $this->error("没有可保存的数据！");
            }
            
        } else {
            $this->error("没有可保存的数据！");
        }
    }
    // ====== 周边城市  结束======
}

?>